/*******************************************************************************
 * File : client.c
 *
 ******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/param.h>    /* ALIGN macro for CMSG_NXTHDR() macro */
#ifdef POSIX
#include <sys/sockio.h>
#endif

#include <errno.h>
#include <netdb.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <sys/time.h>

#define PORT    (int) 56970

extern int errno;

int
main(int argc, char *argv[])
{
    int     sock       = 0,
	n      = 0,
        i = 0,
        j = 0,
	bufsize    = 100,
	server_len = 0;

    char    *buf       = NULL;

    char  hex_lt[3];                   /* temporary buffer to hold hex letters*/

    struct timespec tspc;
    static struct sockaddr_in server,
        client;
    struct hostent *host;   

    fd_set      read_fd;

    memset((void *) &server, 0, sizeof(struct sockaddr_in));
    memset((void *) &client, 0, sizeof(struct sockaddr_in));
    memset((void *) &read_fd, 0, sizeof(fd_set));

    if ( argc < 2 ) { 
    (void)fprintf(stderr,
              "Usage: %s <server-name> <port>\nExample: ./client.exe 127.0.0.1 56970",
              argv[0]);
    exit(1);
    }

    if(!(buf = (char *)calloc(1,bufsize))){
    (void)fprintf(stderr, "Either the system is low on memory\n");
    (void)fprintf(stderr, "or you entered an invalid value\n");
    (void)fprintf(stderr, "with the fourth parameter\n");
    exit(2);
    }

    if (!(host=gethostbyname(argv[1]))){
    perror("CLIENT gethostname ");
    exit(2);
    }
    server.sin_family = AF_INET;
    memcpy(&server.sin_addr, host->h_addr, host->h_length);
    server.sin_port   = htons(atoi(argv[2]));

    if ((sock=socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
	perror("CLIENT socket ");
	exit(3);
    }
    client.sin_family      = AF_INET;
    client.sin_addr.s_addr = htonl(INADDR_ANY);
    client.sin_port    = htons( 0 );

    if (bind(sock, (struct sockaddr *) &client, sizeof(client)) < 0) {
	perror("CLIENT bind ");
	exit(4);
    }

    server_len=sizeof(server);

    if(-1 == connect(sock, (struct sockaddr *) &server, server_len)){
        perror("conf_clnt connect ");
        close(sock);
        exit(6);
    }

    sprintf(buf,"Congratatulations");
    if((n=write(sock, buf, bufsize)) < 0) {
        perror("CLIENT write to socket "); 
            close(sock); 
            exit(6);
    }
        
    printf("Sent 99 bytes to the server");
        
    close(sock);
    free(buf);
    return 0;
}
